package com.goethe.translator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.util.Log;

public class TranslatorHttpRequest extends AsyncTask<String , Void, ArrayList<String>> {

	@Override
	protected ArrayList<String> doInBackground(String... params) {
		String key = params[0];
		String targetLanguage = params[1];
		String originalLanguage = params[2];
    	
    	// We remove white spaces
    	key = key.trim();
        
        // HTTP post
        InputStream is = null;
        BasicNameValuePair keyNVP = new BasicNameValuePair("key", key);
        BasicNameValuePair targetLanguageNVP = new BasicNameValuePair("targetLanguage", targetLanguage);
        BasicNameValuePair originalLanguageNVP = new BasicNameValuePair("originalLanguage", originalLanguage);
        ArrayList<BasicNameValuePair> nvpl = new ArrayList<BasicNameValuePair>();
        nvpl.add(keyNVP);
        nvpl.add(originalLanguageNVP);
        nvpl.add(targetLanguageNVP);
        try {
        	HttpClient httpclient = new DefaultHttpClient();
        	//HttpPost httppost = new HttpPost("http://traductorgoethe.webege.com/translate.php");
        	HttpPost httppost = new HttpPost("http://135.20.205.106/translate.php");
        	httppost.setEntity(new UrlEncodedFormEntity(nvpl));
        	HttpResponse response = httpclient.execute(httppost);
        	HttpEntity entity = response.getEntity();
        	is = entity.getContent();
        	  
        }catch(Exception e){
        	Log.e("DisplayMessageActivity", "Error in http connection: " + e.toString());
        }

        // Convert response to string
        ArrayList<String> response = new ArrayList<String>();
  		try{
  			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
  			
  			String temp;
  			while ((temp = reader.readLine()) != null) {
  				response.add(temp);
  			}
			
  		}catch(Exception e){
  			Log.e("log_tag", "Error obtaining results: " + e.toString());
  		}finally{
  			try {
				is.close();
			} catch (IOException e) {
				Log.e("log_tag", "Error obtaining results: " + e.toString());
			} catch (Exception e) {
				Log.e("log_tag", "Generic exception catched: " + e.toString());
			}
  		}
  		
  		return response;
	}


}
